package cn.com.pc.content.event;

import cn.com.pc.content.constant.LogConstants;
import cn.com.pc.content.service.es.ESCurdService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.rest.RestStatus;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class LogListener {

    private final ESCurdService esCurdService;

    @SneakyThrows
    @Async
    @EventListener(LogEvent.class)
    public void saveLog(LogEvent event) {
        String name = event.name();
        Object source = event.getSource();
        Map<String, Object> params = event.params();

        switch (name) {
            case "createOperationLog": {
                String id = (String) params.get("id");
                RestStatus restStatus = esCurdService.insertWithId(LogConstants.OPERATION_LOG_IDX, id, source);
                if (RestStatus.CREATED != restStatus && RestStatus.OK != restStatus) {
                    log.error("{} 操作日志索引失败:{}", restStatus, source);
                }
                break;
            }
        }
    }
}